package pe.edu.unap.jurado.Servlets;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;

import javax.servlet.*;
import javax.servlet.http.*;

public class GeneraCaptcha extends Servletcito implements Servlet
{
 public GeneraCaptcha()
 {
  fichero = new String("GeneraCaptcha.java");
 }
 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{

	String captcha = new String(GeneraCadena());
	HttpSession sesion = request.getSession(true);
	sesion.setAttribute("Captcha-Sesion", captcha);
	int ancho=150;
	int alto=35;
	BufferedImage imagen = new BufferedImage(ancho, alto, BufferedImage.TYPE_INT_RGB);
	java.io.OutputStream salida = response.getOutputStream();	
	Graphics g = (Graphics) imagen.getGraphics();	
	g.setColor(Color.orange);
	g.fillRect(0, 0, ancho, alto);
	g.setColor(Color.red);
	Font textFont = new Font("Verdana", Font.PLAIN, 26);
	g.setFont(textFont);
	g.setColor(Color.blue);
	
	for(int i=0;i<10;i++) 
	{
		int radioCirculo = (int) (Math.random() * alto / 2.0);
		int circuloX = (int) (Math.random() * ancho - radioCirculo);
		int circuloY = (int) (Math.random() * alto - radioCirculo);
		g.drawOval(circuloX, circuloY, radioCirculo * 2, radioCirculo * 2);
	}
	
	g.setColor(Color.blue);
	g.drawString(captcha,25,25);
	response.setContentType("image/png");
	javax.imageio.ImageIO.write(imagen, "png", salida);
	salida.close();
	}

	public String GeneraCadena()
	{
		String posiblesChars = "abcdefghijklmnopqrstuvwxyz123456789";
		int numChars = 6;
		char[] caracteres = posiblesChars.toCharArray();
		String CadenaFinal="";
				
		for(int i=0;i<numChars;i++) 
		{
			double valorRandom = Math.random();
			int indiceRandom = (int) Math.round(valorRandom * (caracteres.length - 1));
			char caracteresParaMostrar = caracteres[indiceRandom];
			Character C = new Character(caracteresParaMostrar);
			char c = C.charValue();
			String s = C.toString();
			CadenaFinal=CadenaFinal+s;
		}	
		return CadenaFinal;
	}	
}
